<template>
  <div class="log-container">
    <el-card class="filter-card">
      <div class="filter-area">
        <!-- 左侧说明 -->
        <!-- 右侧搜索筛选 -->
        <div class="filter-box">
          <el-form :inline="true" :model="filterForm" class="filter-form">
            <el-form-item label="操作类型">
              <el-select v-model="filterForm.operation_type" placeholder="选择操作类型" clearable>
                <el-option label="全部" value="" />
                <el-option label="登录" value="login" />
                <el-option label="登出" value="logout" />
                <el-option label="查询" value="query" />
                <el-option label="创建" value="create" />
                <el-option label="更新" value="update" />
                <el-option label="删除" value="delete" />
                <el-option label="上传" value="upload" />
                <el-option label="下载" value="download" />
                <el-option label="导入" value="import" />
                <el-option label="导出" value="export" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>

            <el-form-item label="操作用户">
              <el-input v-model="filterForm.user_id" placeholder="用户ID或名称" clearable />
            </el-form-item>

            <el-form-item label="时间范围">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                @change="handleDateChange"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon> 搜索
              </el-button>
              <el-button @click="resetForm">
                <el-icon><RefreshRight /></el-icon> 重置
              </el-button>
              <el-button type="success" @click="handleExport">
                <el-icon><Download /></el-icon> 导出
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>

    <el-card class="table-card">
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
      >
        <!-- <el-table-column prop="id" label="日志ID" width="80" />
        <el-table-column prop="user_id" label="用户ID" width="80" /> -->
        <el-table-column prop="user_id" label="操作用户" width="120" />
        <el-table-column prop="operation_type" label="操作类型" width="100">
          <template #default="scope">
            <el-tag
              :type="getTagType(scope.row.operation_type)"
              size="small"
            >
              {{ formatOperationType(scope.row.operation_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operation_type" label="操作模块" width="120" />
        <el-table-column prop="operation_content" label="操作描述" show-overflow-tooltip />
        <el-table-column prop="operation_ip" label="IP地址" width="120" />
        <el-table-column prop="operation_result" label="状态" width="80">
          <template #default="scope">
            <el-tag
              :type="scope.row.operation_result === 'success' ? 'success' : 'danger'"
              size="small"
            >
              {{ scope.row.operation_result === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operation_time" label="操作时间" width="180" />
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button type="primary" size="small" circle @click.stop="handleViewDetail(scope.row)">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      title="日志详情"
      v-model="detailDialogVisible"
      width="700px"
      destroy-on-close
    >
      <div v-if="currentLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日志ID">{{ currentLog.id }}</el-descriptions-item>
          <el-descriptions-item label="操作用户">{{ currentLog.username }} (ID: {{ currentLog.user_id }})</el-descriptions-item>
          <el-descriptions-item label="操作类型">
            <el-tag :type="getTagType(currentLog.operation_type)">
              {{ formatOperationType(currentLog.operation_type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentLog.ip_address }}</el-descriptions-item>
          <el-descriptions-item label="操作模块">{{ currentLog.module }}</el-descriptions-item>
          <el-descriptions-item label="操作状态">
            <el-tag :type="currentLog.status === 'success' ? 'success' : 'danger'">
              {{ currentLog.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="操作时间" :span="2">{{ currentLog.created_at }}</el-descriptions-item>
          <el-descriptions-item label="操作描述" :span="2">{{ currentLog.description }}</el-descriptions-item>
          <el-descriptions-item label="客户端信息" :span="2">{{ currentLog.user_agent }}</el-descriptions-item>
          <el-descriptions-item label="请求路径" :span="2">{{ currentLog.request_url }}</el-descriptions-item>
          <el-descriptions-item label="请求方法">{{ currentLog.request_method }}</el-descriptions-item>
          <el-descriptions-item label="响应状态码">{{ currentLog.response_code }}</el-descriptions-item>
          <el-descriptions-item label="请求参数" :span="2">
            <div class="code-block">{{ formatJson(currentLog.request_params) }}</div>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentLog.status === 'failed'" label="错误信息" :span="2">
            <div class="error-message">{{ currentLog.error_message }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, RefreshRight, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getOperationLogs } from '@/api/system'

// 定义组件名
defineOptions({
  name: 'OperationLog'
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 当前查看的日志
const currentLog = ref(null)
const detailDialogVisible = ref(false)

// 获取一个月前的日期
const getOneMonthAgo = () => {
  const today = new Date()
  const oneMonthAgo = new Date()
  oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1)

  // 格式化日期为 YYYY-MM-DD
  const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }

  return [formatDate(oneMonthAgo), formatDate(today)]
}

// 日期范围，默认为最近一个月
const dateRange = ref(getOneMonthAgo())

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 筛选表单
const filterForm = reactive({
  operation_type: '',
  user_id: '',
  start_time: dateRange.value[0], // 默认设置开始时间
  end_time: dateRange.value[1]    // 默认设置结束时间
})

// 获取日志列表
const fetchLogList = async () => {
  loading.value = true
  // 构建请求参数
  const params = {
    skip: (pagination.currentPage - 1) * pagination.pageSize,
    limit: pagination.pageSize,
    ...filterForm
  }

  try {
    const res = await getOperationLogs(params)

    // 检查返回的数据结构
    if (res && res.items && Array.isArray(res.items)) {
      tableData.value = res.items
      pagination.total = res.total || 0
    } else {
      console.error('未能识别API返回的数据结构:', res)
      tableData.value = []
      pagination.total = 0
      ElMessage.error('获取操作日志失败，API返回格式不正确')
    }
  } catch (error) {
    ElMessage.error('获取操作日志失败: ' + (error.message || '未知错误'))
    console.error('获取操作日志失败:', error)
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 初始化数据
onMounted(() => {
  // 初始化时已经设置了默认日期范围
  fetchLogList()
})

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchLogList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchLogList()
}

// 日期范围变化
const handleDateChange = (val) => {
  if (val && val.length === 2) {
    filterForm.start_time = val[0]
    filterForm.end_time = val[1]
  } else {
    filterForm.start_time = ''
    filterForm.end_time = ''
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchLogList()
}

// 重置表单
const resetForm = () => {
  // 重置为默认值而不是清空
  filterForm.operation_type = ''
  filterForm.user_id = ''
  const defaultDateRange = getOneMonthAgo()
  filterForm.start_time = defaultDateRange[0]
  filterForm.end_time = defaultDateRange[1]
  dateRange.value = defaultDateRange

  pagination.currentPage = 1
  fetchLogList()
}

// 导出日志
const handleExport = () => {
  ElMessage.success('日志导出成功')
}

// 查看日志详情
const handleViewDetail = (row) => {
  currentLog.value = row
  detailDialogVisible.value = true
}

// 格式化操作类型
const formatOperationType = (type) => {
  const typeMap = {
    login: '登录',
    logout: '登出',
    query: '查询',
    create: '创建',
    update: '更新',
    delete: '删除',
    upload: '上传',
    download: '下载',
    import: '导入',
    export: '导出',
    other: '其他'
  }
  return typeMap[type] || type
}

// 获取标签类型
const getTagType = (type) => {
  const typeMap = {
    login: 'success',
    logout: 'info',
    query: '',
    create: 'primary',
    update: 'warning',
    delete: 'danger',
    upload: 'success',
    download: 'info',
    import: 'warning',
    export: 'success',
    other: 'info'
  }
  return typeMap[type] || 'info'
}

// 格式化JSON
const formatJson = (json) => {
  if (!json) return ''
  try {
    if (typeof json === 'string') {
      return JSON.stringify(JSON.parse(json), null, 2)
    } else {
      return JSON.stringify(json, null, 2)
    }
  } catch {
    // 忽略错误
    return json
  }
}
</script>

<style scoped>
.log-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 180px);
  box-sizing: border-box;
}

.filter-card {
  margin-bottom: 20px;
  width: 100%;
}

.filter-area {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
}

.filter-title {
  max-width: 300px;
}

.filter-title h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: #303133;
}

.sub-title {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.filter-box {
  margin-left: 20px;
  display: flex;
  justify-content: flex-end;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.table-card {
  flex: 1;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-table) {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.log-detail {
  max-height: 500px;
  overflow-y: auto;
}

.code-block {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 8px;
  font-family: monospace;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 150px;
  overflow-y: auto;
}

.error-message {
  color: #f56c6c;
  background-color: #fef0f0;
  padding: 8px;
  border-radius: 4px;
  white-space: pre-wrap;
}
</style>
